package com.flowplan.ai.service;

import com.flowplan.ai.client.TongyiClient;
import com.flowplan.ai.client.TongyiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * AI服务实现类
 * 
 * @author FlowPlan Team
 */
@Slf4j
@Service
public class AiService {
    
    @Autowired
    private TongyiClient tongyiClient;
    
    @Value("${ai.features.requirement-analysis}")
    private boolean requirementAnalysisEnabled;
    
    @Value("${ai.features.document-generation}")
    private boolean documentGenerationEnabled;
    
    @Value("${ai.features.smart-suggestions}")
    private boolean smartSuggestionsEnabled;
    
    /**
     * 需求分析
     */
    public AiAnalysisResult analyzeRequirement(String requirementText) {
        log.info("开始AI需求分析，内容长度: {}", requirementText.length());
        
        if (!requirementAnalysisEnabled) {
            return AiAnalysisResult.disabled("需求分析功能已禁用");
        }
        
        try {
            TongyiResponse response = tongyiClient.analyzeRequirements(requirementText);
            
            if (response.isSuccess()) {
                return AiAnalysisResult.success(
                    response.getContent(),
                    extractAnalysisMetrics(response.getContent())
                );
            } else {
                return AiAnalysisResult.failure("AI分析失败: " + 
                    (response.getError() != null ? response.getError().getMessage() : "未知错误"));
            }
            
        } catch (Exception e) {
            log.error("需求分析异常: {}", e.getMessage(), e);
            return AiAnalysisResult.failure("需求分析异常: " + e.getMessage());
        }
    }
    
    /**
     * 生成功能设计文档
     */
    public AiDocumentResult generateFunctionSpec(String requirement) {
        log.info("开始生成功能设计文档");
        
        if (!documentGenerationEnabled) {
            return AiDocumentResult.disabled("文档生成功能已禁用");
        }
        
        try {
            TongyiResponse response = tongyiClient.generateFunctionSpec(requirement);
            
            if (response.isSuccess()) {
                return AiDocumentResult.success(
                    "功能设计文档",
                    response.getContent(),
                    "markdown"
                );
            } else {
                return AiDocumentResult.failure("文档生成失败: " + 
                    (response.getError() != null ? response.getError().getMessage() : "未知错误"));
            }
            
        } catch (Exception e) {
            log.error("文档生成异常: {}", e.getMessage(), e);
            return AiDocumentResult.failure("文档生成异常: " + e.getMessage());
        }
    }
    
    /**
     * 生成测试用例
     */
    public AiDocumentResult generateTestCases(String functionality) {
        log.info("开始生成测试用例");
        
        if (!documentGenerationEnabled) {
            return AiDocumentResult.disabled("文档生成功能已禁用");
        }
        
        try {
            TongyiResponse response = tongyiClient.generateTestCases(functionality);
            
            if (response.isSuccess()) {
                return AiDocumentResult.success(
                    "测试用例文档",
                    response.getContent(),
                    "markdown"
                );
            } else {
                return AiDocumentResult.failure("测试用例生成失败: " + 
                    (response.getError() != null ? response.getError().getMessage() : "未知错误"));
            }
            
        } catch (Exception e) {
            log.error("测试用例生成异常: {}", e.getMessage(), e);
            return AiDocumentResult.failure("测试用例生成异常: " + e.getMessage());
        }
    }
    
    /**
     * 智能建议
     */
    public AiSuggestionResult getSmartSuggestions(String projectContext) {
        log.info("获取智能建议");
        
        if (!smartSuggestionsEnabled) {
            return AiSuggestionResult.disabled("智能建议功能已禁用");
        }
        
        try {
            TongyiResponse response = tongyiClient.getSmartSuggestions(projectContext);
            
            if (response.isSuccess()) {
                return AiSuggestionResult.success(
                    response.getContent(),
                    extractSuggestionCategories(response.getContent())
                );
            } else {
                return AiSuggestionResult.failure("智能建议生成失败: " + 
                    (response.getError() != null ? response.getError().getMessage() : "未知错误"));
            }
            
        } catch (Exception e) {
            log.error("智能建议异常: {}", e.getMessage(), e);
            return AiSuggestionResult.failure("智能建议异常: " + e.getMessage());
        }
    }
    
    /**
     * 从Excel内容生成待办任务建议
     */
    public AiTaskGenerationResult generateTodoSuggestions(String excelContent) {
        log.info("基于Excel内容生成待办任务建议");
        
        String prompt = String.format(
            "基于以下Excel需求内容，生成相应的待办任务建议：\n\n%s\n\n" +
            "请按照8步标准流程生成待办任务：\n" +
            "1. 沟通确认\n" +
            "2. 排期安排\n" +
            "3. 文档编写\n" +
            "4. 数据源核查\n" +
            "5. 开发实现\n" +
            "6. 测试验证\n" +
            "7. UAT验收\n" +
            "8. 发布上线\n\n" +
            "对每个步骤，请提供：\n" +
            "- 任务标题\n" +
            "- 任务描述\n" +
            "- 预估工时\n" +
            "- 优先级建议",
            excelContent
        );
        
        try {
            TongyiResponse response = tongyiClient.sendChatRequest(prompt);
            
            if (response.isSuccess()) {
                return AiTaskGenerationResult.success(
                    response.getContent(),
                    extractTaskSuggestions(response.getContent())
                );
            } else {
                return AiTaskGenerationResult.failure("任务生成失败: " + 
                    (response.getError() != null ? response.getError().getMessage() : "未知错误"));
            }
            
        } catch (Exception e) {
            log.error("任务生成异常: {}", e.getMessage(), e);
            return AiTaskGenerationResult.failure("任务生成异常: " + e.getMessage());
        }
    }
    
    /**
     * 提取分析指标
     */
    private Map<String, Object> extractAnalysisMetrics(String content) {
        Map<String, Object> metrics = new HashMap<>();
        
        // 简单的指标提取逻辑，实际可以更复杂
        metrics.put("contentLength", content.length());
        metrics.put("estimatedComplexity", content.length() > 1000 ? "高" : content.length() > 500 ? "中" : "低");
        metrics.put("analysisTime", System.currentTimeMillis());
        
        return metrics;
    }
    
    /**
     * 提取建议分类
     */
    private Map<String, Object> extractSuggestionCategories(String content) {
        Map<String, Object> categories = new HashMap<>();
        
        // 简单的分类提取逻辑
        categories.put("hasProjectManagement", content.contains("项目管理"));
        categories.put("hasTechnical", content.contains("技术"));
        categories.put("hasRisk", content.contains("风险"));
        categories.put("hasOptimization", content.contains("优化"));
        
        return categories;
    }
    
    /**
     * 提取任务建议
     */
    private Map<String, Object> extractTaskSuggestions(String content) {
        Map<String, Object> suggestions = new HashMap<>();
        
        // 简单的任务提取逻辑
        suggestions.put("taskCount", content.split("\\n").length);
        suggestions.put("hasHighPriority", content.contains("高优先级"));
        suggestions.put("totalEstimatedHours", extractEstimatedHours(content));
        
        return suggestions;
    }
    
    /**
     * 提取预估工时
     */
    private int extractEstimatedHours(String content) {
        // 简单的工时提取逻辑，实际可以使用正则表达式
        return content.split("小时").length * 8; // 假设每个任务平均8小时
    }
    
    /**
     * 检查AI服务状态
     */
    public AiServiceStatus getServiceStatus() {
        return AiServiceStatus.builder()
                .requirementAnalysisEnabled(requirementAnalysisEnabled)
                .documentGenerationEnabled(documentGenerationEnabled)
                .smartSuggestionsEnabled(smartSuggestionsEnabled)
                .apiConnected(checkApiConnection())
                .build();
    }
    
    /**
     * 检查API连接状态
     */
    private boolean checkApiConnection() {
        try {
            TongyiResponse response = tongyiClient.sendChatRequest("测试连接");
            return response.isSuccess();
        } catch (Exception e) {
            return false;
        }
    }
}